package com.eairlv.share.auto.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eairlv.share.auto.entity.Result;
import com.eairlv.share.auto.entity.bo.ShareTableForm;
import com.eairlv.share.auto.entity.bo.ShareTableSearchForm;
import com.eairlv.share.auto.entity.po.ShareTablePO;
import com.eairlv.share.auto.entity.po.enums.ShareWay;
import com.eairlv.share.auto.entity.vo.ShareTableVO;
import com.eairlv.share.auto.mapper.ShareTableMapper;
import com.eairlv.share.auto.utils.BeanUtil;
import com.eairlv.share.auto.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author eairlv
 * @description
 * @date 11:23 2020/1/16
 */
@Slf4j
@Service
public class ShareTableService {

    @Autowired
    ShareTableMapper shareTableMapper;

    /**
     * 查询分片规则
     * @param shareTableSearchForm
     * @return
     */
    public Result<List<ShareTableVO>> getShareRule(ShareTableSearchForm shareTableSearchForm) {
        return Result.ok(getShareByIdOrTemplateTableName(shareTableSearchForm.getShareTableId(), shareTableSearchForm.getTemplateTableName())
                .parallelStream()
                .map(e -> BeanUtil.copyProperties(e, ShareTableVO.class))
                .collect(Collectors.toList()));
    }

    /**
     * 创建分片规则
     * @param shareTableForm
     * @return
     */
    public Result<Integer> addShareRule(ShareTableForm shareTableForm) {
        ShareTablePO shareTablePO = BeanUtil.copyProperties(shareTableForm, ShareTablePO.class);
        Result<Integer> result = checkShareRule(shareTablePO);
        if (result == null){
            if (shareTableForm.getId() == null){
                shareTablePO.setCreateTime(System.currentTimeMillis());
                insert(shareTablePO);
            } else {
                shareTablePO.setModifyTime(System.currentTimeMillis());
                update(shareTablePO);
            }
            return Result.ok(shareTablePO.getId());
        } else {
            return result;
        }
    }

    /**
     * 检查分片规则
     * @param shareTablePO
     * @return
     */
    private Result<Integer> checkShareRule(ShareTablePO shareTablePO){
        // 分表参数判断
        if (StrUtil.isNotBlank(shareTablePO.getTemplateTableName())
                && shareTablePO.getShareTableWay() != null
                && shareTablePO.getShareTableInterval() != null
                && shareTablePO.getShareTableInterval() > 0
                && shareTablePO.getShareTableAdvance() != null
                && shareTablePO.getShareTableAdvance() >= 0){
            // 分区参数判断
            if (shareTablePO.getSharePartitionWay() == null){
                shareTablePO.setSharePartitionWay(ShareWay.NONE);
            }
            if (shareTablePO.getSharePartitionWay() != ShareWay.NONE){
                if (StrUtil.isBlank(shareTablePO.getTemplatePartitionField())
                        || shareTablePO.getSharePartitionInterval() == null
                        || shareTablePO.getSharePartitionInterval().equals(0)
                        || shareTablePO.getShareTableWay().getCode() >= shareTablePO.getSharePartitionWay().getCode()){
                    return Result.failMessage("invalid shareTablePartition parameter");
                }
            }
            // 装载初始值
            long currentTimeMillis = System.currentTimeMillis();
            if (shareTablePO.getShareTableBegin() == null || shareTablePO.getShareTableBegin() == 0){
                shareTablePO.setShareTableBegin(currentTimeMillis);
            }
            if (shareTablePO.getCheckInterval() == null){
                shareTablePO.setCheckInterval(0);
            }
            shareTablePO.setLastCheckTime(currentTimeMillis);
            return null;
        }
        return Result.failMessage("invalid shareTable parameter");
    }

    /**
     * 删除分片规则
     * @param id
     * @return
     */
    public Result<Integer> deleteShareRule(Integer id) {
        return Result.ok(delete(id));
    }

    /**
     * 插入分片规则
     * @param shareTablePO
     * @return
     */
    public Integer insert(ShareTablePO shareTablePO){
        shareTableMapper.insert(shareTablePO);
        return shareTablePO.getId();
    }

    /**
     * 更新分片规则
     * @param shareTablePO
     * @return
     */
    public Integer update(ShareTablePO shareTablePO){
        shareTableMapper.updateById(shareTablePO);
        return shareTablePO.getId();
    }

    /**
     * 删除分片规则
     * @param id
     * @return
     */
    public Integer delete(Integer id){
        shareTableMapper.deleteById(id);
        return id;
    }

    /**
     * 通过shareTableId或templateTableName查询分片规则
     * @param shareTableId
     * @return
     */
    public List<ShareTablePO> getShareByIdOrTemplateTableName(Integer shareTableId, String templateTableName){
        QueryWrapper<ShareTablePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(shareTableId != null, "id", shareTableId);
        queryWrapper.eq(StrUtil.isNotBlank(templateTableName), "template_table_name", templateTableName);
        return shareTableMapper.selectList(queryWrapper);
    }

    /**
     * 通过shareTableId查询分片规则
     * @param shareTableId
     * @return
     */
    public ShareTablePO getShareById(Integer shareTableId){
        return shareTableMapper.selectById(shareTableId);
    }

    /**
     * 通过templateTableName查询分片规则
     * @param templateTableName
     * @return
     */
    public ShareTablePO getShareByTemplateTableName(String templateTableName){
        try {
            QueryWrapper<ShareTablePO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("template_table_name", templateTableName);
            return shareTableMapper.selectOne(queryWrapper);
        } catch (Exception e){
            log.warn("ShareTableService getShareById error: {}", LogUtil.getExceptionMessage(e));
            return null;
        }
    }

}
